package com.atguigu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV1;
import com.atguigu.realtime.bean.UserLoginBean;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lzc
 * @Date 2022/5/28 10:09
 */
public class Dws_04_DwsUserUserLoginWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_04_DwsUserUserLoginWindow().init(3004,
                                                 2,
                                                 "Dws_04_DwsUserUserLoginWindow",
                                                 Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }
    
    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {
        // 1. 过滤出登录记录
        SingleOutputStreamOperator<JSONObject> loginStream = filterLoginData(stream);
        // 2. 找到当日首次登录和回流记录, 封装到pojo
        SingleOutputStreamOperator<UserLoginBean> beanStream = findFirstLoginAndBack(loginStream);
        // 3. 开窗聚合
        SingleOutputStreamOperator<UserLoginBean> aggregatedStream = windowAndAggregate(beanStream);
        
        // 4. 写出到clickhouse中
        writeToClickHouse(aggregatedStream);
        
    }
    
    private void writeToClickHouse(SingleOutputStreamOperator<UserLoginBean> aggregatedStream) {
        aggregatedStream.addSink(FlinkSinkUtil.getClickHouseSink(Constant.CLICKHOUSE_DB,"dws_user_user_login_window", UserLoginBean.class));
    }
    
    private SingleOutputStreamOperator<UserLoginBean> windowAndAggregate(SingleOutputStreamOperator<UserLoginBean> stream) {
       return stream
            .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<UserLoginBean>() {
                    @Override
                    public UserLoginBean reduce(UserLoginBean b1,
                                                UserLoginBean b2) throws Exception {
                        b1.setUuCt(b1.getUuCt() + b2.getUuCt());
                        b1.setBackCt(b1.getBackCt() + b2.getBackCt());
                        
                        return b1;
                    }
                },
                new ProcessAllWindowFunction<UserLoginBean, UserLoginBean, TimeWindow>() {
                    @Override
                    public void process(Context ctx,
                                        Iterable<UserLoginBean> elements,
                                        Collector<UserLoginBean> out) throws Exception {
                        String stt = AtguiguUtil.toDateTime(ctx.window().getStart());
                        String edt = AtguiguUtil.toDateTime(ctx.window().getEnd());
    
                        UserLoginBean bean = elements.iterator().next();
                        bean.setStt(stt);
                        bean.setEdt(edt);
                        bean.setTs(System.currentTimeMillis());
                        out.collect(bean);
                    }
                }
            );
    }
    
    private SingleOutputStreamOperator<UserLoginBean> findFirstLoginAndBack(
        SingleOutputStreamOperator<JSONObject> stream) {
        return stream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getLong("ts"))
            )
            .keyBy(obj -> obj.getJSONObject("common").getString("uid"))
            .process(new KeyedProcessFunction<String, JSONObject, UserLoginBean>() {
                
                private ValueState<String> lastLoginDateState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    lastLoginDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastLoginDateState", String.class));
                }
                
                @Override
                public void processElement(JSONObject obj,
                                           Context ctx,
                                           Collector<UserLoginBean> out) throws Exception {
                    Long ts = obj.getLong("ts");
                    String today = AtguiguUtil.toDate(ts);
                    String lastLoginDate = lastLoginDateState.value();
                    
                    long uuCt = 0;
                    long backCt = 0;
                    
                    if (!today.equals(lastLoginDate)) {
                        // 今天第一次登录
                        uuCt = 1;
                        if (lastLoginDate != null) {  // 表示这个用户曾经登录过
                            //今天第一次登录, 并且曾经登录过, 判断 登录日期是否相差大于7天
                            long todayTs = AtguiguUtil.toTs(today, "yyyy-MM-dd");
                            long lastLoginDateTs = AtguiguUtil.toTs(lastLoginDate, "yyyy-MM-dd");
    
                            if ((todayTs - lastLoginDateTs) / 1000 / 60 / 60 / 24 > 7) {
                                backCt = 1;
                            }
                        }
                        lastLoginDateState.update(today);
                    }
    
                    if (uuCt == 1) {
                        out.collect(new UserLoginBean("", "", backCt,uuCt,ts));
                    }
                    
                }
            });
    }
    
    private SingleOutputStreamOperator<JSONObject> filterLoginData(DataStreamSource<String> stream) {
        return stream
            .map(JSON::parseObject)
            .filter(obj -> {
                String uid = obj.getJSONObject("common").getString("uid");
                JSONObject page = obj.getJSONObject("page");
                String lastPageId = page.getString("last_page_id");
                // 如果是入口也并且uid不是null, 自动登录
                // uid不是null, 并且上个页面是登录页面, 证明从登录页面跳转过来的
                return uid != null
                    && (lastPageId == null || "login".equals(lastPageId));
            });
    }
}
/*
统计七日回流用户和当日独立用户数

数据源: 日志数据  页面日志

1. 找出来用户的登录记录
    如果登录成功 uid is not null
    
    如果是自动登录  last_page_id is null
    
    如果中途调整登录  last_page_id is login
    
    保留当天的第一个登录记录
      去重
        转态
    
2.  当日独立用户
        每条记录都是
        
     
     七日回流
        7天前登录过, 今天又登录, 则是7日回流
        
        状态: 保留的是最后一次登录时间
            今天的登录时间-最后一次登录时间>7
            
....
 */
